/**
 * Created by xinchunting on 17-9-24.
 */
/**
 * Created by Shaka on 12/21/16.
 */
$.validator.setDefaults({
    highlight: function (e) {
        $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
    }, success: function (e) {
        e.closest(".form-group").removeClass("has-error").addClass("has-success");
    }, errorElement: "span", errorPlacement: function (e, r) {
        e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
    }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
});
var iNotify = new iNotify({
    message: '有消息了。',//标题
    effect: 'flash', // flash | scroll 闪烁还是滚动
    openurl: "http://www.bing.com", // 点击弹窗打开连接地址
    onclick: function () { //点击弹出的窗之行事件
        console.log("---")
    },
    //可选播放声音
    audio: {
        //可以使用数组传多种格式的声音文件
        file: ''
        //下面也是可以的哦
        //file: 'msg.mp4'
    },
    //标题闪烁，或者滚动速度
    interval: 1000,
    //可选，默认绿底白字的  Favicon
    updateFavicon: {
        // favicon 字体颜色
        textColor: "#fff",
        //背景颜色，设置背景颜色透明，将值设置为&ldquo;transparent&rdquo;
        backgroundColor: "#2F9A00"
    },
    //可选chrome浏览器通知，默认不填写就是下面的内容
    notification: {
        title: "通知！",//设置标题
        icon: "",//设置图标 icon 默认为 Favicon
        body: '您来了一条新消息'//设置消息内容
    }
});
var width = $(".jqGrid_wrapper").width();
$(".datepicker").datepicker({
    todayBtn: "linked",
    clearBtn: true,
    autoclose: true,
    language: "zh-CN"
});

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);  //获取url中"?"符后的字符串并正则匹配
    var context = "";
    if (r != null)
        context = r[2];
    reg = null;
    r = null;
    return context == null || context == "" || context == "undefined" ? "" : context;
}

var Config = {
    createUrl: "/api/admin/dc/dcBookkeeping/create",
    selectDcBookKeepingUrl: "/api/admin/dc/DcBookkeeping/get",
    selectDcBookkeepingTitle: "/api/admin/dc/dcBookkeeping/title/get",
    selectDcBookkeepingDcOrderProd: "/api/admin/dc/dcBookkeeping/dcOrderProd/get"
};
$('#submitCreate').click(function () {
    $("#companyId").val(getQueryString("id"));
    $("#dcBookKeepingForm").validate({
        rules: {
            categoryId: {
                selectcheck: true
            }
        }
    });
    if ($('#dcBookKeepingForm').valid()) {
        var postData = $('#dcBookKeepingForm').serializeArray();
        $.ajax({
            url: Config.createUrl,
            type: "POST",
            data: postData,
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                iNotify.notify({
                    title: "操作成功",
                    body: "已创建事项"
                });
                jQuery("#dc_bookKeeping").trigger("reloadGrid");
                jQuery("#management").trigger("reloadGrid");
                $('#item').val("");
                $('#unitPrice').val("");
                $('#quantity').val("");
                $('#Subtotal').val("");
                $('#actualPrice').val("");
                $('#remark').val("");
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });
        return false;
    }
});

$("input[id=quantity]").blur(function () {
    if ($("input[id=unitPrice]").val() != "" && $("input[id=quantity]").val() != "") {
        $("input[id=Subtotal]").val($("input[id=unitPrice]").val() * $("input[id=quantity]").val());
    }
});

$(document).ready(function () {
    $.jgrid.defaults.styleUI = "Bootstrap";
    $("#dc_bookKeeping").jqGrid({
        datatype: "json",
        url: Config.selectDcBookKeepingUrl,
        postData: {companyId: getQueryString("id")},
        height: 300,
        autowidth: true,
        shrinkToFit: true,
        rowNum: 12,
        colNames: ["事项ID", "事项名称", "单价", "数量", "实际价格", "备注", "时间", "操作"],
        colModel: [{
            name: "id",
            index: "id",
            search: true
        }, {
            name: "item",
            index: "item"
        }, {
            name: "unitPrice",
            index: "unitPrice"
        }, {
            name: "quantity",
            index: "quantity",
            sorttype: "int"
        }, {
            name: "actualPrice",
            index: "actualPrice",
            sorttype: "int"
        }, {
            name: "remark",
            index: "remark"
        }, {
            name: "ctime",
            index: "ctime"
        }, {
            name: "operate",
            index: "operate",
            sortable: false
        }],
        pager: "#pager_dc_bookKeeping",
        jsonReader: {
            root: "data", "page": "page", total: "total",
            records: "records", repeatitems: false, id: "id"
        },
        viewrecords: true,
        hidegrid: false,
        gridComplete: function () {
            dc_bookKeeping();
        }
    });
    jQuery("#dc_bookKeeping").jqGrid('navGrid', '#pager_dc_bookKeeping', {
        add: false, edit: false, del: false, search: false,
        refresh: false
    });
    // jQuery('#goods_list').trigger('reloadGrid');
    $(window).bind("resize", function () {
        width = $(".jqGrid_wrapper").width();
        $("#dc_bookKeeping").setGridWidth(width);
    });


    $("#dc_turnover").jqGrid({
        datatype: "json",
        url: Config.selectDcBookkeepingDcOrderProd,
        height: 300,
        postData: {companyId: getQueryString("id")},
        autowidth: true,
        shrinkToFit: true,
        colNames: ["ID", "名称", "数量", "收益价格","操作"],
        colModel: [{
            name: "id",
            index: "id",
            search: true
        }, {
            name: "name",
            index: "name"
        }, {
            name: "num",
            index: "num"
        }, {
            name: "price",
            index: "price",
            sorttype: "int"
        },{
            name: "operate",
            index: "operate",
            sortable: false
        }],
        pager: "#pager_turnover",
        jsonReader: {
            root: "data", "page": "page", total: "total",
            records: "records", repeatitems: false, id: "id"
        },
        viewrecords: true,
        hidegrid: false,
        gridComplete: function () {
            dc_turnover();
        }
    });
    jQuery("#dc_turnover").jqGrid('navGrid', '#pager_turnover', {
        add: false, edit: false, del: false, search: false,
        refresh: false
    });
    // jQuery('#goods_list').trigger('reloadGrid');
    $(window).bind("resize", function () {
        width = $(".jqGrid_wrapper").width();
        $("#dc_turnover").setGridWidth(width);
    });


    $("#management").jqGrid({
        datatype: "json",
        url: Config.selectDcBookkeepingTitle,
        height: 300,
        postData: {companyId: getQueryString("id")},
        autowidth: true,
        shrinkToFit: true,
        colNames: ["ID", "总支出", "总收入", "总利润"],
        colModel: [{
            name: "id",
            index: "id",
            search: true
        }, {
            name: "actualPrice",
            index: "actualPrice"
        }, {
            name: "unitPrice",
            index: "unitPrice"
        }, {
            name: "quantity",
            index: "quantity"
        }],
        pager: "#pager_management",
        jsonReader: {
            root: "data", "page": "page", total: "total",
            records: "records", repeatitems: false, id: "id"
        },
        viewrecords: true,
        hidegrid: false,
        gridComplete: function () {
            management();
        }
    });
    jQuery("#management").jqGrid('navGrid', '#pager_management', {
        add: false, edit: false, del: false, search: false,
        refresh: false
    });
    $(window).bind("resize", function () {
        width = $(".jqGrid_wrapper").width();
        $("#management").setGridWidth(width);
    });
});


$("#dc_bookKeeping_search").click(function () {
    var postdata = $("#dc_bookKeeping").jqGrid('getGridParam', 'postData');
    var stime = dateToEpoch($("#beginDateOne").val()) * 1 - 8 * 60 * 60 * 1000 + 1;
    var etime = dateToEpoch($("#endDateOne").val()) * 1 + 16 * 60 * 60 * 1000 - 1;
    if (!stime || !etime) {
        alert("请输入时间")
    }
    postdata._search = true;
    postdata.stime = stime;
    postdata.etime = etime;
    jQuery("#dc_bookKeeping").trigger("reloadGrid", postdata);
});
$("#dc_turnover_search").click(function () {
    var postdata = $("#dc_turnover").jqGrid('getGridParam', 'postData');
    var stime = dateToEpoch($("#beginDateTwo").val()) * 1 - 8 * 60 * 60 * 1000 + 1;
    var etime = dateToEpoch($("#endDateTwo").val()) * 1 + 16 * 60 * 60 * 1000 - 1;
    if (!stime || !etime) {
        alert("请输入时间")
    }
    postdata._search = true;
    postdata.stime = stime;
    postdata.etime = etime;
    jQuery("#dc_turnover").trigger("reloadGrid", postdata);
});
$("#management_search").click(function () {
    var postdata = $("#management").jqGrid('getGridParam', 'postData');
    var stime = dateToEpoch($("#beginDateThree").val()) * 1 - 8 * 60 * 60 * 1000 + 1;
    var etime = dateToEpoch($("#endDateThree").val()) * 1 + 16 * 60 * 60 * 1000 - 1;
    if (!stime || !etime) {
        alert("请输入时间")
    }
    postdata._search = true;
    postdata.stime = stime;
    postdata.etime = etime;
    jQuery("#management").trigger("reloadGrid", postdata);
});
function dc_bookKeepingDelete(id, index) {
    dc_bookKeepingUpdateDialog("DELETE", Config.deleteCompanyCommentUrl + '/' + id);
    jQuery("#dc_bookKeeping").jqGrid('delRowData', id);
}


function dc_turnoverDelete(id, index) {
    dc_turnoverUpdateDialog("DELETE", Config.deleteDishCommentUrl + '/' + id);
    jQuery("#dc_turnover").jqGrid('delRowData', id);
}

function managementDelete(id, index) {
    managementUpdateDialog("DELETE", Config.deleteDishCommentUrl + '/' + id);
    jQuery("#management").jqGrid('delRowData', id);
}

function dc_bookKeepingUpdateDialog(action, url) {
    $.ajax(
        {
            url: url,
            type: action,
            success: function (data, textStatus, jqXHR) {
                if (action == 'DELETE') {
                    jQuery("#dc_dish").trigger("reloadGrid");

                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error(errorThrown);
            }
        });
}
function dc_turnoverUpdateDialog(action, url) {
    $.ajax(
        {
            url: url,
            type: action,
            success: function (data, textStatus, jqXHR) {
                if (action == 'DELETE') {
                    jQuery("#dc_dish").trigger("reloadGrid");

                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error(errorThrown);
            }
        });
}

function managementUpdateDialog(action, url) {
    $.ajax(
        {
            url: url,
            type: action,
            success: function (data, textStatus, jqXHR) {
                if (action == 'DELETE') {
                    jQuery("#dc_dish").trigger("reloadGrid");

                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error(errorThrown);
            }
        });
}
function dc_bookKeeping() {
    var ids = jQuery("#dc_bookKeeping").jqGrid('getDataIDs');
    for (var i = 0; i < ids.length; i++) {
        var id = ids[i];
        var dataFromTheRow = jQuery('#dc_bookKeeping').jqGrid('getRowData', id);
        dataFromTheRow.ctime = new Date(dataFromTheRow.ctime * 1).yyyymmddhhmmss();
        // var html = "<a style='color:#f60;padding-right: 15px'>删除</a>";
        // html += '<a class="J_menuItem" style="color:#f60;padding-right: 15px" data-index="0">修改</a>';
        jQuery("#dc_bookKeeping").jqGrid('setRowData', ids[i], {
            // operate: html,
            ctime: dataFromTheRow.ctime,
            unitPrice: toFixedForPrice(dataFromTheRow.unitPrice),
            actualPrice: toFixedForPrice(dataFromTheRow.actualPrice),
        });
    }
}

function dc_turnover() {
    var ids = jQuery("#dc_turnover").jqGrid('getDataIDs');
    for (var i = 0; i < ids.length; i++) {
        var id = ids[i];
        var dataFromTheRow = jQuery('#dc_turnover').jqGrid('getRowData', id);
        dataFromTheRow.ctime = new Date(dataFromTheRow.ctime * 1).yyyymmddhhmmss();
        jQuery("#dc_turnover").jqGrid('setRowData', ids[i], {
            price: toFixedForPrice(dataFromTheRow.price),
            ctime: dataFromTheRow.ctime
        });
    }
}
function management() {
    var ids = jQuery("#management").jqGrid('getDataIDs');
    for (var i = 0; i < ids.length; i++) {
        var id = ids[i];
        var dataFromTheRow = jQuery('#management').jqGrid('getRowData', id);
        jQuery("#management").jqGrid('setRowData', ids[i], {
            actualPrice: toFixedForPrice(dataFromTheRow.actualPrice),
            unitPrice: toFixedForPrice(dataFromTheRow.unitPrice),
            quantity: toFixedForPrice(dataFromTheRow.quantity)
        });
    }
}
$("#ul li").click(function () {
    $("#dc_bookKeeping").setGridWidth(width);
    $("#dc_turnover").setGridWidth(width);
    $("#management").setGridWidth(width);
});

